import { getTokenOverview, getUserRanking, getModelStats, exportTokenStats } from '@/api/tokenStats'

export default {
  data() {
    return {
      // 日期范围
      dateRange: [],

      // 概览数据
      overviewData: {
        totalTokens: 0,
        totalCost: 0,
        activeUsers: 0,
        totalChats: 0,
        avgTokensPerChat: 0,
        dailyStats: []
      },

      // 用户排行数据
      userRankingData: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },

      // 模型统计数据
      modelStatsData: []
    }
  },

  methods: {
    // 初始化日期范围（默认最近7天）
    initDateRange() {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      this.dateRange = [
        this.formatDate(start),
        this.formatDate(end)
      ]
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 日期范围变化处理
    handleDateRangeChange(value) {
      this.dateRange = value
      this.refreshData()
    },

    // 刷新所有数据
    async refreshData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadOverviewData(),
          this.loadUserRankingData(),
          this.loadModelStatsData()
        ])
        this.$message.success('数据刷新成功')
      } catch (error) {
        this.$message.error('数据刷新失败')
      } finally {
        this.loading = false
      }
    },

    // 加载概览数据
    async loadOverviewData() {
      try {
        const dateRangeStr = this.dateRange ? this.dateRange.join(',') : ''
        const response = await getTokenOverview(dateRangeStr)
        if (response.code === 1) {
          this.overviewData = response.data || {}
        }
      } catch (error) {
        console.error('加载概览数据失败:', error)
        this.$message.error('加载概览数据失败')
      }
    },

    // 加载用户排行数据
    async loadUserRankingData() {
      this.userRankingLoading = true
      try {
        const params = {
          page: this.pagination.page,
          pageSize: this.pagination.pageSize
        }
        const response = await getUserRanking(params)
        if (response.code === 1) {
          const records = response.data?.records || []
          // 添加排名字段
          this.userRankingData = records.map((item, index) => ({
            ...item,
            rank: (this.pagination.page - 1) * this.pagination.pageSize + index + 1
          }))
          this.pagination.total = response.data?.total || 0
        }
      } catch (error) {
        console.error('加载用户排行数据失败:', error)
        this.$message.error('加载用户排行数据失败')
      } finally {
        this.userRankingLoading = false
      }
    },

    // 加载模型统计数据
    async loadModelStatsData() {
      this.modelStatsLoading = true
      try {
        const dateRangeStr = this.dateRange ? this.dateRange.join(',') : ''
        const response = await getModelStats(dateRangeStr)
        if (response.code === 1) {
          this.modelStatsData = response.data || []
        }
      } catch (error) {
        console.error('加载模型统计数据失败:', error)
        this.$message.error('加载模型统计数据失败')
      } finally {
        this.modelStatsLoading = false
      }
    },

    // 刷新用户排行
    refreshUserRanking() {
      this.pagination.page = 1
      this.loadUserRankingData()
    },

    // 刷新模型统计
    refreshModelStats() {
      this.loadModelStatsData()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.page = 1
      this.loadUserRankingData()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.page = val
      this.loadUserRankingData()
    },

    // 导出数据
    async exportData() {
      this.exportLoading = true
      try {
        const dateRangeStr = this.dateRange ? this.dateRange.join(',') : ''
        const response = await exportTokenStats(dateRangeStr)

        // 创建下载链接
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `token统计_${this.dateRange[0]}_${this.dateRange[1]}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        this.$message.success('数据导出成功')
      } catch (error) {
        console.error('导出数据失败:', error)
        this.$message.error('导出数据失败')
      } finally {
        this.exportLoading = false
      }
    },

    // 获取排名标签类型
    getRankType(rank) {
      if (rank === 1) return 'danger'
      if (rank === 2) return 'warning'
      if (rank === 3) return 'success'
      return ''
    },

    // 格式化数字
    formatNumber(num) {
      if (!num) return '0'
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },

    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '-'
      try {
        const date = new Date(dateTimeStr)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } catch (error) {
        return dateTimeStr
      }
    }
  }
}
